package cn.org.xuanzp.nty.utils;

import cn.org.xuanzp.common.command.Command;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname ClientsUtil
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/9/24 23:37
 * @Created by xuanzp
 */
public class NettyServerUtil {

    private static String namespace;
    private static String nodeid;
    private static NODE_TYPE nodeType;

    public static void route(String toId, Command command) {

    }

    public static enum NODE_TYPE{
        ENDPOINT("1","暴漏端点"),
        CLOUD("2","集群"),
        ;
        private String value;
        private String desc;

        NODE_TYPE(String value, String desc) {
            this.value = value;
            this.desc = desc;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }
    }

    private static Map<String, ChannelHandlerContext> clients = new HashMap<String, ChannelHandlerContext>();

    public static Boolean existCtx(String clientId){
        Boolean containsKey = clients.containsKey(clientId);
        if(containsKey){
            ChannelHandlerContext channelHandlerContext = clients.get(clientId);
            containsKey = (!channelHandlerContext.isRemoved()) && channelHandlerContext.channel().isActive();
        }
        return containsKey;
    }

    public static void addCtx(String clientId, ChannelHandlerContext ctx){
        clients.put(clientId, ctx);
    }

    public static void removeCtx(String clientId){
        clients.remove(clientId);
    }

    public static void transmit(String clientId, Object msg){
        if(!clients.containsKey(clientId)){
            System.err.println("clientId not exist");
            return;
        }
        ChannelHandlerContext ctx = clients.get(clientId);
        if(!ctx.isRemoved() && ctx.channel().isActive()){
            ctx.channel().writeAndFlush(msg);
        }else {
            System.err.println("clientId connect exception");
        }

    }

    public static String getNamespace() {
        return namespace;
    }

    public static void setNamespace(String namespace) {
        NettyServerUtil.namespace = namespace;
    }

    public static String getNodeid() {
        return nodeid;
    }

    public static void setNodeid(String nodeid) {
        NettyServerUtil.nodeid = nodeid;
    }
}
